<template>
  <div class="project-list-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">项目列表</span>
          <div class="header-actions">
            <el-button @click="showAIDialog = true" type="primary">
              <el-icon><MagicStick /></el-icon>
              AI创建项目
            </el-button>
            <el-button type="success" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新建项目
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="项目名称">
          <el-input v-model="searchForm.name" placeholder="请输入项目名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 视图切换 -->
      <div class="view-switch">
        <el-radio-group v-model="viewMode">
          <el-radio-button label="card">
            <el-icon><Grid /></el-icon>
            卡片视图
          </el-radio-button>
          <el-radio-button label="list">
            <el-icon><List /></el-icon>
            列表视图
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 卡片视图 -->
      <el-row v-if="viewMode === 'card'" :gutter="20" style="margin-top: 20px" v-loading="loading">
        <el-col :span="8" v-for="project in paginatedProjects" :key="project.id">
          <el-card class="project-card" shadow="hover">
            <div class="project-header">
              <div class="project-icon" :style="{ background: getStatusColor(project.status) }">
                <el-icon :size="32"><Folder /></el-icon>
              </div>
              <div class="project-info">
                <h3>{{ project.name }}</h3>
                <p>{{ project.description }}</p>
              </div>
            </div>

            <el-divider />

            <div class="project-meta">
              <div class="meta-item">
                <span class="label">负责人：</span>
                <el-avatar :size="24">{{ project.owner }}</el-avatar>
              </div>
              <div class="meta-item">
                <span class="label">进度：</span>
                <el-progress :percentage="project.progress" :color="getProgressColor(project.progress)" />
              </div>
              <div class="meta-item">
                <span class="label">截止：</span>
                <span>{{ project.deadline }}</span>
              </div>
              <div class="meta-item">
                <span class="label">状态：</span>
                <el-tag :type="getStatusType(project.status)">{{ getStatusLabel(project.status) }}</el-tag>
              </div>
            </div>

            <div class="project-stats">
              <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>{{ project.memberCount }}人</span>
              </div>
              <div class="stat-item">
                <el-icon><Document /></el-icon>
                <span>{{ project.taskCount }}任务</span>
              </div>
              <div class="stat-item">
                <el-icon><Clock /></el-icon>
                <span>剩余{{ project.remainDays }}天</span>
              </div>
            </div>

            <div class="project-actions">
              <el-button type="primary" @click="handleViewKanban(project)">
                <el-icon><Grid /></el-icon>
                看板
              </el-button>
              <el-button @click="handleViewGantt(project)">
                <el-icon><TrendCharts /></el-icon>
                甘特图
              </el-button>
              <el-dropdown @command="(cmd) => handleCommand(cmd, project)">
                <el-button>
                  更多
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="edit">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item command="team">
                      <el-icon><User /></el-icon>
                      团队
                    </el-dropdown-item>
                    <el-dropdown-item command="archive" divided>
                      <el-icon><FolderOpened /></el-icon>
                      归档
                    </el-dropdown-item>
                    <el-dropdown-item command="delete">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 列表视图 -->
      <el-table v-else :data="paginatedProjects" border style="margin-top: 20px" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="项目名称" width="200" />
        <el-table-column prop="description" label="项目描述" show-overflow-tooltip />
        <el-table-column prop="owner" label="负责人" width="100" />
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" :color="getProgressColor(row.progress)" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deadline" label="截止日期" width="120" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewKanban(row)">看板</el-button>
            <el-button link type="primary" @click="handleViewGantt(row)">甘特图</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[9, 18, 36, 54]"
          :total="filteredProjects.length"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建项目对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="owner">
          <el-select v-model="form.owner" placeholder="选择负责人">
            <el-option label="张三" value="张三" />
            <el-option label="李四" value="李四" />
            <el-option label="王五" value="王五" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="截止日期" prop="deadline">
          <el-date-picker v-model="form.deadline" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="项目优先级" prop="priority">
          <el-radio-group v-model="form.priority">
            <el-radio label="low">低</el-radio>
            <el-radio label="medium">中</el-radio>
            <el-radio label="high">高</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- AI创建对话框 -->
    <el-dialog v-model="showAIDialog" title="AI创建项目" width="600px">
      <el-alert
        title="描述你的项目，AI会自动生成项目结构和任务分解"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-input
        v-model="aiInput"
        type="textarea"
        :rows="5"
        placeholder="例如：创建一个ERP系统开发项目，包含需求分析、UI设计、前端开发、后端开发、测试、上线等阶段"
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAICreate" :loading="aiCreating">
          <el-icon><MagicStick /></el-icon>
          AI生成
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  MagicStick, Plus, Grid, List, Folder, User, Document, Clock,
  TrendCharts, ArrowDown, Edit, FolderOpened, Delete
} from '@element-plus/icons-vue'
import {usePage} from "@/uses/usePage.js";
import {defineStore} from "pinia";

const router = useRouter()
const searchStore = defineStore('productStore', {
  state: () => {
    return {
      searchObject: {
        no: 1,
        size: 1000, // 树形结构一次性加载
        sortField: "id",
        sortMethod: "desc",
        shop: '',
        name: '',
        code: ''
      }
    }
  }
})

const { searchObject } = searchStore()

const {pageData, sizeChange, pageChange, search, changeTableSort, loading} = usePage("/project/search", searchObject);


const viewMode = ref('card')
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  page: 1,
  size: 9
})

const dialogVisible = ref(false)
const dialogTitle = ref('新建项目')
const showAIDialog = ref(false)
const aiInput = ref('')
const aiCreating = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  name: '',
  description: '',
  owner: '',
  startDate: '',
  deadline: '',
  priority: 'medium'
})

const rules = {
  name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  owner: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }]
}

// 存储所有项目数据
const allProjects = ref([])

// 生成模拟数据
const generateMockData = () => {
  const projectNames = [
    'ERP系统开发', '商城小程序', 'CRM系统升级', '数据分析平台', '移动APP开发',
    '智能仓储系统', '在线教育平台', '供应链管理', '物联网平台', '区块链应用',
    '人工智能客服', '财务管理系统', 'OA办公系统', '电商平台', '云存储系统',
    '直播系统', '社交APP', '短视频平台', '游戏开发', '知识付费平台',
    '招聘管理系统', '考试系统', '医疗管理', '餐饮管理', '酒店管理',
    '智慧停车', '智能家居', '车联网系统'
  ]

  const descriptions = [
    '开发新一代智能管理系统', '微信小程序开发项目', '系统功能升级改造',
    '企业级应用平台', 'H5混合开发', '云原生架构设计',
    '大数据分析处理', '高并发分布式系统', 'AI智能化升级'
  ]

  const owners = ['张三', '李四', '王五', '赵六', '钱七', '孙八']
  const statuses = ['active', 'completed', 'paused']
  const statusWeights = [0.6, 0.3, 0.1] // 各状态的权重

  const projects = []
  for (let i = 0; i < 28; i++) {
    // 根据权重选择状态
    const rand = Math.random()
    let status = 'active'
    let cumWeight = 0
    for (let j = 0; j < statuses.length; j++) {
      cumWeight += statusWeights[j]
      if (rand <= cumWeight) {
        status = statuses[j]
        break
      }
    }

    const progress = status === 'completed' ? 100 :
                    status === 'paused' ? Math.floor(Math.random() * 60) + 10 :
                    Math.floor(Math.random() * 90) + 10

    const remainDays = status === 'completed' ? 0 : Math.floor(Math.random() * 120) + 10

    projects.push({
      id: i + 1,
      name: projectNames[i % projectNames.length] + (i > projectNames.length - 1 ? ` ${Math.floor(i / projectNames.length) + 1}` : ''),
      description: descriptions[Math.floor(Math.random() * descriptions.length)],
      owner: owners[Math.floor(Math.random() * owners.length)],
      progress: progress,
      status: status,
      deadline: `2025-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
      memberCount: Math.floor(Math.random() * 10) + 3,
      taskCount: Math.floor(Math.random() * 50) + 10,
      remainDays: remainDays
    })
  }
  return projects
}

// 筛选后的项目
const filteredProjects = computed(() => {
  return allProjects.value.filter(project => {
    if (searchForm.name && !project.name.includes(searchForm.name)) {
      return false
    }
    if (searchForm.status && project.status !== searchForm.status) {
      return false
    }
    return true
  })
})

// 分页后的项目
const paginatedProjects = computed(() => {
  const start = (pagination.page - 1) * pagination.size
  const end = start + pagination.size
  return filteredProjects.value.slice(start, end)
})

const getStatusColor = (status) => {
  const colors = {
    active: '#409eff',
    completed: '#67c23a',
    paused: '#e6a23c'
  }
  return colors[status] || '#909399'
}

const getStatusType = (status) => {
  const types = {
    active: 'primary',
    completed: 'success',
    paused: 'warning'
  }
  return types[status] || ''
}

const getStatusLabel = (status) => {
  const labels = {
    active: '进行中',
    completed: '已完成',
    paused: '已暂停'
  }
  return labels[status] || status
}

const getProgressColor = (progress) => {
  if (progress < 30) return '#f56c6c'
  if (progress < 70) return '#e6a23c'
  return '#67c23a'
}

const handleSearch = () => {
  loading.value = true
  pagination.page = 1 // 搜索时重置到第一页
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询成功')
  }, 300)
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
}

const handleCurrentChange = (page) => {
  pagination.page = page
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const handleAdd = () => {
  dialogTitle.value = '新建项目'
  Object.assign(form, {
    id: null,
    name: '',
    description: '',
    owner: '',
    startDate: '',
    deadline: '',
    priority: 'medium'
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑项目'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.id) {
        // 编辑
        const index = allProjects.value.findIndex(p => p.id === form.id)
        if (index > -1) {
          allProjects.value[index] = {
            ...allProjects.value[index],
            ...form
          }
        }
        ElMessage.success('更新成功')
      } else {
        // 新增
        const newId = Math.max(...allProjects.value.map(p => p.id), 0) + 1
        allProjects.value.push({
          id: newId,
          name: form.name,
          description: form.description,
          owner: form.owner,
          startDate: form.startDate,
          deadline: form.deadline,
          priority: form.priority,
          progress: 0,
          status: 'active',
          memberCount: Math.floor(Math.random() * 10) + 3,
          taskCount: 0,
          remainDays: Math.ceil((new Date(form.deadline) - new Date()) / (1000 * 60 * 60 * 24))
        })
        ElMessage.success('新建成功')
      }
      dialogVisible.value = false
    }
  })
}

const handleViewKanban = (project) => {
  router.push({ name: 'ProjectKanban', params: { id: project.id } })
}

const handleViewGantt = (project) => {
  router.push({ name: 'ProjectGantt', params: { id: project.id } })
}

const handleCommand = (cmd, project) => {
  switch (cmd) {
    case 'edit':
      handleEdit(project)
      break
    case 'team':
      router.push({
        path: '/project/team',
        query: { projectId: project.id, projectName: project.name }
      })
      break
    case 'archive':
      ElMessage.success('已归档项目：' + project.name)
      break
    case 'delete':
      handleDelete(project)
      break
  }
}

const handleDelete = (project) => {
  ElMessageBox.confirm(`确定删除项目 "${project.name}"？`, '警告', {
    type: 'warning'
  }).then(() => {
    const index = allProjects.value.findIndex(p => p.id === project.id)
    if (index > -1) {
      allProjects.value.splice(index, 1)
    }

    // 如果当前页没有数据，跳转到上一页
    const maxPage = Math.ceil(filteredProjects.value.length / pagination.size) || 1
    if (pagination.page > maxPage) {
      pagination.page = maxPage
    }

    ElMessage.success('删除成功')
  })
}

const handleAICreate = () => {
  if (!aiInput.value.trim()) {
    ElMessage.warning('请输入项目描述')
    return
  }

  aiCreating.value = true

  setTimeout(() => {
    ElMessage.success('AI已生成项目结构和任务分解')
    showAIDialog.value = false
    aiCreating.value = false
    dialogVisible.value = true

    Object.assign(form, {
      name: 'AI生成的项目',
      description: aiInput.value,
      owner: '张三',
      priority: 'high'
    })
  }, 2000)
}

// 初始化数据
onMounted(() => {
  loading.value = true
  setTimeout(() => {
    allProjects.value = generateMockData()
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.project-list-page {
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.view-switch {
  margin-bottom: 20px;
}

.project-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.project-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0,0,0,0.15);
}

.project-header {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}

.project-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.project-info {
  flex: 1;
}

.project-info h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.project-info p {
  margin: 0;
  font-size: 13px;
  color: #606266;
}

.project-meta {
  margin-bottom: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 13px;
}

.meta-item .label {
  min-width: 70px;
  color: #909399;
}

.project-stats {
  display: flex;
  justify-content: space-around;
  padding: 15px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #606266;
}

.project-actions {
  display: flex;
  gap: 10px;
}

.project-actions .el-button {
  flex: 1;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

